<template>
  <!-- 个人主页 -->
  <k-scroll class="profile-scroll" topColor="#FEFEFE" bottomColor="var(--main-background-color)" topType="stretch" bottomType="stretch">
    <!-- 文件选择 -->
    <input id="upload" v-show="false" type="file" accept="image/*" @change="chooseFile" />
    <!-- 选择器(性别) -->
    <van-popup v-model="showPicker1" round position="bottom">
      <van-picker show-toolbar :columns="columns1" @cancel="showPicker1 = false" @confirm="onConfirm1" />
    </van-popup>
    <!-- 选择器(生日) -->
    <van-popup v-model="showPicker2" round position="bottom">
      <van-picker show-toolbar :columns="columns2" @cancel="showPicker2 = false" @confirm="onConfirm2" />
    </van-popup>
    <!-- 修改个人信息弹窗 -->
    <k-popup
      class="popup"
      v-model="popShow"
      :popWidth="popWidth"
      :popHeight="popHeight"
      :popHiddenX="popHiddenX"
      :popHiddenY="popHiddenY"
      :popShowX="popShowX"
      :popShowY="popShowY"
      :rotate="rotate"
      :useScale="useScale"
      :useOpacity="useOpacity"
      :outside="outside"
    >
      <!-- 弹窗内容 -->
      <div class="popupStyle" @touchmove.stop>
        <div class="top-box">
          <img class="close" src="@/assets/img/icons/black/close.svg" @click="popShow = false" />
          <div class="title">编辑个人资料</div>
          <div class="save" :style="{ color: nickname_input ? '#101010' : '#CECECE' }" @click="submit">保存</div>
        </div>
        <k-scroll
          class="scroll"
          topColor="var(--main-background-color)"
          bottomColor="var(--main-background-color)"
          topType="stretch"
          bottomType="stretch"
        >
          <div class="content">
            <div class="avatar-box">
              <img id="avatar" class="avatar-change" :src="$store.state.userInfo.avatar" />
              <div class="camera-box" @click="avatarClick">
                <img class="camera" src="@/assets/img/icons/white/camera.svg" />
              </div>
            </div>
            <div class="item">
              <div class="item-title">昵称</div>
              <div class="value">
                <input maxlength="8" class="input-nickname" type="text" v-model="nickname_input" />
              </div>
            </div>
            <div class="item" @click="showPicker1 = true">
              <div class="item-title">性别</div>
              <div class="value">
                <span>{{ gender }}</span>
                <img class="enter" src="@/assets/img/icons/enter.svg" />
              </div>
            </div>
            <div class="item" @click="showPicker2 = true">
              <div class="item-title">生日</div>
              <div class="value">
                <span>{{ birthday }}</span>
                <img class="enter" src="@/assets/img/icons/enter.svg" />
              </div>
            </div>
            <div class="item">
              <div class="item-title">签名</div>
              <div class="value">
                <input maxlength="12" class="input-sign" type="text" v-model="sign" placeholder="介绍一下你自己" />
              </div>
            </div>
          </div>
        </k-scroll>
      </div>
    </k-popup>
    <div class="profile">
      <div class="userInfo">
        <img class="back" src="@/assets/img/icons/black/back.svg" @click="$router.back()" />
        <div class="avatar-editor">
          <img id="avatar2" class="avatar" :src="$store.state.userInfo.avatar" @click="lookAvatar" />
          <k-button class="btn-editor" bgColor="#FE6100" fontSize="0.13rem" fontColor="#FEFEFE" @click="popShow = !popShow"> 编辑资料</k-button>
        </div>
        <div class="nickname">{{ $store.state.userInfo.nickname }}</div>
        <div class="read-record">
          <span>阅读</span>
          <span style="font-size: 0.18rem; margin-left: 0.06rem">{{ $store.state.userInfo.books }}</span>
          <span style="margin-left: 0.06rem">本书</span>
          <span style="margin-left: 0.06rem"> ▪ </span>
          <span style="font-size: 0.18rem; margin-left: 0.06rem">{{ $store.state.userInfo.readseconds | formatH }}</span>
          <span style="margin-left: 0.06rem">时</span>
          <span style="font-size: 0.18rem; margin-left: 0.06rem">{{ $store.state.userInfo.readseconds | formatS }}</span>
          <span style="margin-left: 0.06rem">分</span>
        </div>
        <div class="gold">
          <span>金币余额：</span>
          <span style="font-size: 0.18rem">{{ $store.state.userInfo.gold }}</span>
          <k-button class="btn-account" bgColor="#FE6100" fontSize="0.13rem" fontColor="#FEFEFE" @click="$router.push('/goldAccount')">
            明细</k-button
          >
        </div>
        <div v-if="!$store.state.userInfo.invitepeople" class="input-invite-code">
          <k-button class="btn" bgColor="#FE6100" fontSize="0.13rem" fontColor="#FEFEFE" @click="$router.push('/inviteCode')">填写邀请码</k-button>
          <span class="span">(可获得300金币奖励)</span>
        </div>
      </div>
      <div class="more">
        <div class="title">欢乐大转盘</div>
        <div class="sign">
          <k-button
            v-if="new Date().getTime() - $store.state.userInfo.signintime >= 24 * 60 * 60 * 1000"
            class="btn"
            bgColor="#FE6100"
            fontSize="0.13rem"
            fontColor="#FEFEFE"
            @click="signClick"
            >签到</k-button
          >
          <k-button
            v-if="new Date().getTime() - $store.state.userInfo.signintime < 24 * 60 * 60 * 1000"
            class="btn"
            :disable="true"
            bgColor="#909497"
            fontSize="0.13rem"
            fontColor="#FEFEFE"
            >已签到</k-button
          >
          <div class="rule" @click="showRule">活动规则</div>
        </div>
        <div class="circle1">
          <div class="circle2"></div>
          <div class="circle3">
            <div
              class="small_circle"
              v-for="a in 24"
              :key="a"
              :style="{
                transform: 'rotate(' + a * 15 + 'deg)',
                backgroundColor: (a + (lamp ? 1 : 0)) % 2 ? 'rgb(255, 255, 255)' : 'rgb(255, 127, 42)',
              }"
            ></div>
          </div>
          <div class="circle4"></div>
          <div class="circle5">
            <div
              class="triangle"
              v-for="a in 8"
              :key="a"
              :style="{ transform: 'rotate(' + a * 45 + 'deg)', borderTop: a % 2 ? '1.1rem solid #E9E0FF' : '1.1rem solid #7021E8' }"
            ></div>
            <div
              class="prize"
              v-for="(item, index) in prize"
              :key="JSON.parse(item)"
              :style="{ transform: 'rotate(' + ((index + 1) * 45 + 30) + 'deg)', color: (index + 1) % 2 ? '#E9E0FF' : '#7021E8' }"
            >
              <img class="gold" src="@/assets/img/icons/gold.png" />
              <div class="number">{{ item }}金币</div>
            </div>
            <div class="pointer" id="pointer" :style="{ transform: 'rotate(' + rotatePointer + 'deg)', transition: transition }">
              <div class="pointer2"></div>
              <div class="circle"></div>
              <div class="circle2"></div>
              <div class="circle3" @click="start">{{ rotating ? '' : '抽奖' }}</div>
            </div>
          </div>
        </div>
        <div class="chance">你剩余{{ times }}次抽奖机会</div>
      </div>
    </div>
  </k-scroll>
</template>

<script>
//初始化数据
let year = []
let month = []
let day = []
let nowtime = new Date().getTime() //当前时间戳
for (let i = 0; i < 100; i++) {
  year.push(new Date(nowtime).getFullYear() + i - 99)
}
for (let i = 0; i < 12; i++) {
  month.push(i + 1 > 9 ? i + 1 : '0' + (i + 1))
}
for (let i = 0; i < 30; i++) {
  day.push(i + 1 > 9 ? i + 1 : '0' + (i + 1))
}
import * as imageConversion from 'image-conversion' //引入前端图片操作库
import { ImagePreview } from 'vant' //引入vant的图片预览API
export default {
  name: 'profile',
  watch: {
    //限制不能出现空格
    nickname_input(value) {
      this.nickname_input = value.replace(/\s|[\r\n]/g, '')
    },
    //限制不能出现空格
    sign(value) {
      console.log(value)
      this.sign = value.replace(/\s|[\r\n]/g, '')
    },
  },
  data() {
    return {
      times: this.$store.state.userInfo.lotterytimes, //可用抽奖次数
      prize: [10, 888, 50, 666, 200, 100, 500, 30], //奖品
      lamp: false, //转盘灯
      result: -1, //中奖结果
      id: 0, //定时器id
      rotatePointer: 0, //旋转角度
      transition: '', //过渡时间
      rotating: false, //正在旋转
      nickname_input: this.$store.state.userInfo.nickname, //用户输入昵称
      gender: this.$store.state.userInfo.gender, //用户性别
      birthday: this.$store.state.userInfo.birthday, //用户生日
      sign: this.$store.state.userInfo.introduce, //个人签名
      showPicker1: false, //是否显示选择器(性别)
      showPicker2: false, //是否显示选择器(生日)
      columns1: ['男', '女', '未知'], //picker数据列表(性别)
      popWidth: 100, //对话框的宽度，单位相对于浏览器的百分比
      popHeight: 62, //对话框的高度，单位相对于浏览器的百分比
      popHiddenX: 0, //对话框隐藏时的X位置，单位相对于浏览器的百分比
      popHiddenY: 100, //对话框隐藏时的Y位置，单位相对于浏览器的百分比
      popShowX: 0, //对话框出现时的X位置，单位相对于浏览器的百分比
      popShowY: 38, //对话框出现时的Y位置，单位相对于浏览器的百分比
      popShow: false, //是否显示对话框
      rotate: 0, //过渡旋转角度
      useScale: false, //缩放属性
      useOpacity: true, //使用透明度变化
      outside: true, //开启外部点击关闭弹窗

      //picker数据列表(生日)
      columns2: [
        // 第一列
        {
          values: year,
          defaultIndex: year.length - 1,
        },
        // 第二列
        {
          values: month,
          defaultIndex: 0,
        },
        // 第三列
        {
          values: day,
          defaultIndex: 0,
        },
      ],
    }
  },
  //过滤器
  filters: {
    //格式化小时
    formatH(s) {
      return Math.floor(s / 3600)
    },
    //格式化分钟
    formatS(s) {
      return Math.floor(s / 60) % 60
    },
  },
  methods: {
    //头像被点击
    avatarClick() {
      document.getElementById('upload').click()
    },
    //查看头像
    lookAvatar() {
      ImagePreview([this.$store.state.userInfo.avatar])
    },
    //选择器确定选择结果(性别)
    onConfirm1(value) {
      this.gender = value
      this.showPicker1 = false
    },
    //选择器确定选择结果(生日)
    onConfirm2(value) {
      this.birthday = value.join('-')
      this.showPicker2 = false
    },
    //显示转盘规则
    showRule() {
      this.$dialog({
        title: '活动说明',
        messageAlign: 'left',
        message: '1、每日签到可获得50金币奖励和1次抽奖;\n2、累计签到满7天可获得额外300金币和3次抽奖;\n3、抽奖次数可叠加;',
      })
    },
    //更新用户信息
    getUserInfo() {
      //刷新用户信息
      this.$updateUserInfo().then((data) => {
        this.nickname_input = this.$store.state.userInfo.nickname
        this.gender = this.$store.state.userInfo.gender
        this.birthday = this.$store.state.userInfo.birthday
        this.sign = this.$store.state.userInfo.introduce
      })
    },
    //用户签到
    signClick() {
      this.$network
        .main('postNull', 'signIn')
        .then((data) => {
          this.$dialog({
            message: '签到成功！恭喜获得50金币奖励和1次抽奖机会！',
          }).then((data) => {
            this.getUserInfo() //更新用户信息
            this.times++
          })
        })
        .catch((err) => {
          //报错
          this.$dialog({
            message: err,
          })
        })
    },
    //提交资料编辑
    submit() {
      if (!this.nickname_input) return
      this.$network
        .main('changeUserInfo', this.nickname_input, this.gender, this.birthday, this.sign)
        .then((data) => {
          this.$toast({
            type: 'success',
            message: '修改成功',
          })
          this.popShow = false //关闭修改界面
          this.getUserInfo() //刷新用户信息
        })
        .catch((err) => {
          this.$toast({
            type: 'fail',
            message: err,
          })
          this.popShow = false //关闭修改界面
        })
    },
    //开始转盘
    start() {
      if (this.$store.state.userInfo.lotterytimes <= 0) {
        this.$dialog({
          message: '您没有抽奖次数！',
        })
        return
      }
      if (this.rotating) return //正在旋转中，返回
      let r = Math.round(Math.random() * 999) //随机数
      let deg = 0 //旋转角度
      //中奖10金币
      if (r >= 0 && r <= 499) {
        deg = Math.random() * 35 + 50
        this.result = 0
      }
      //中奖30金币
      if (r >= 500 && r <= 799) {
        deg = Math.random() * 35 + 5
        this.result = 7
      }
      //中奖50金币
      if (r >= 800 && r <= 899) {
        deg = Math.random() * 35 + 50 + 45 + 45
        this.result = 2
      }
      //中奖100金币
      if (r >= 900 && r <= 949) {
        deg = Math.random() * 35 + 50 + 45 + 45 + 45 + 45 + 45
        this.result = 5
      }
      //中奖200金币
      if (r >= 950 && r <= 979) {
        deg = Math.random() * 35 + 50 + 45 + 45 + 45 + 45
        this.result = 4
      }
      //中奖500金币
      if (r >= 980 && r <= 989) {
        deg = Math.random() * 35 + 50 + 45 + 45 + 45 + 45 + 45 + 45
        this.result = 6
      }
      //中奖666金币
      if (r >= 990 && r <= 998) {
        deg = Math.random() * 35 + 50 + 45 + 45 + 45
        this.result = 3
      }
      //中奖888金币
      if (r >= 999 && r <= 999) {
        deg = Math.random() * 35 + 50 + 45
        this.result = 1
      }
      //提交抽奖结果
      this.$network
        .main('lotteryResult', this.prize[this.result])
        .then((data) => {
          this.times-- //减少抽奖次数
          this.rotating = true
          this.transition = '12s'
          this.rotatePointer = Math.round(deg + 3600) //指针旋转度数
          //变换转盘灯
          this.id = setInterval(() => {
            this.lamp = !this.lamp
          }, 100)
          //停止灯变换
          setTimeout(() => {
            clearInterval(this.id)
          }, 12000)
          setTimeout(() => {
            this.$dialog({
              message: '恭喜抽中' + this.prize[this.result] + '金币！',
            }).then((data) => {
              this.transition = '0s'
              this.rotatePointer = 0
              this.rotating = false
              this.getUserInfo() //更新用户信息
            })
          }, 13000)
        })
        .catch((err) => {
          //报错
          this.$dialog({
            message: err,
          })
        })
    },
    //文件选择完成
    chooseFile(e) {
      if (document.getElementById('upload').files.length != 1) return //未选择图片
      let filetype = document.getElementById('upload').files[0].type //获取图片类型
      let filesize = document.getElementById('upload').files[0].size //获取图片大小
      if (filesize >= 1024 * 1024 * 20) {
        this.$dialog.alert({
          message: '图片不能大于20MB',
        })
        return
      }
      let ratio // 压缩系数
      switch (true) {
        case filesize > 1024 * 50 && filesize < 1024 * 200:
          ratio = 0.5
          break
        case filesize >= 1024 * 200 && filesize < 1024 * 1024:
          ratio = 0.3
          break
        case filesize >= 1024 * 1024 && filesize < 1024 * 1024 * 20:
          ratio = 0.1
          break
        default:
          ratio = 1
          break
      }
      if (filetype == 'image/gif') ratio = 1 //gif不能压缩，否则不能动了
      this.$toast({
        message: '原图:' + Math.round(filesize / 1024) + 'kb,压缩后:' + Math.round((filesize / 1024) * ratio) + 'kb',
        position: 'bottom',
      })
      //开始上传图片
      const toast = this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: '上传中...',
      })
      imageConversion
        .compressAccurately(e.target.files[0], {
          size: Math.round((filesize / 1024) * ratio), //压缩后的大小kb
        })
        .then((data) => {
          return imageConversion.filetoDataURL(data)
        })
        .then((data) => {
          document.getElementById('avatar').src = data //预览图片
          // document.getElementById('avatar2').src = data //预览图片
          return this.$network.main('changeAvatar', data.length, filetype, data.split(',')[1], (e) => {
            console.log('上传进度：' + e + '%')
          })
        })
        .then((data) => {
          toast.clear()
          this.$toast({
            message: '上传完成',
            position: 'bottom',
          })
          this.getUserInfo() //获取用户信息
        })
        .catch((err) => {
          toast.clear()
          this.$dialog({
            title: '修改失败',
            message: err,
          })
        })
    },
  },
}
</script>

<style scoped src="./index.less" lang="less"></style>
